package com.hb.trans.mvp.presenter

import com.basiclib.base.BasePresenter
import com.basiclib.lifecycle.RxLifecycleUtils
import com.basiclib.network.RetryWithDelay
import com.basiclib.network.RxErrorHandler
import com.hb.trans.bean.Base
import com.hb.trans.bean.Update
import com.hb.trans.bean.VersionInfo
import com.hb.trans.global.ErrorHandleSubscriber
import com.hb.trans.mvp.contract.UserCenterContract
import com.hb.trans.mvp.model.UserCenterModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject

class UserCenterPresenter @Inject constructor(model: UserCenterModel, var errorHandler: RxErrorHandler) :
    BasePresenter<UserCenterContract.View, UserCenterContract.Model>(model) {

    fun getVersionInfo() {
        mModel.checkUpdate()
            .subscribeOn(Schedulers.io())
            .retryWhen(RetryWithDelay())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxLifecycleUtils.bindToLifecycle(mRootView!!))
            .subscribe(object : ErrorHandleSubscriber<Base<VersionInfo>>(errorHandler) {
                override fun next(r: Base<VersionInfo>) {
                    if (r.code == 1) {
                        mRootView?.updateInfo(r.data)
                    } else {
                        mRootView?.showShortToast(r.info ?: "")
                    }
                }
            })
    }

    fun getById() {
        mModel.getById()
            .subscribeOn(Schedulers.io())
            .retryWhen(RetryWithDelay())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxLifecycleUtils.bindToLifecycle(mRootView!!))
            .subscribe(object : ErrorHandleSubscriber<Base<Update>>(errorHandler) {
                override fun next(r: Base<Update>) {
                    if (r.code == 1) {
                        mRootView?.setGetById(r.data)
                    } else {
                        mRootView?.showShortToast(r.info ?: "")
                    }
                }
            })
    }

}